/*
 * Copyright (c) 2023.11.29 Fengxun
 * Version:5.2.2
 */

const {
  getCheckpointList,
  saveCheckpointList,
  getCheckpointByID
} = require("../../utils/initdata")
const {
  getPageConfig,
  saveRemoteRecord,
  saveRemoteGold
} = require("../../utils/custom_loading")
const {
  calculateDistance
} = require("../../utils/gps")

// pages/main/task.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    task_type: 0,
    show: false,
    show_next: false,
    show_gps: false,
    show_beacon: false,
    show_prompt: false,
    question_item_list: [],
    message_content: [],
    message_content_css: '',
    message_content_all_css: '',
    message_confirm: '',
    message_image: '',
    message_image_css: '',
    message_front_image: '',
    message_front_image_css: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const config = getPageConfig('task')
    if (config) {
      this.setData({
        config: config
      })
    }

    this.checkpoint_list = getCheckpointList()
    // console.log('checkpoint_list', this.checkpoint_list, options.id)
    this.checkpoint = getCheckpointByID(this.checkpoint_list, options.id)
    // console.log('checkpoint', this.checkpoint)
    this.setData({
      isWelcome: wx.getStorageSync('welcome'),
      next_word: this.checkpoint.status === 3 ? '点击退出' : '点击继续'
    })
    this.getTaskList()
  },

  getTaskList() {
    if (typeof (this.checkpoint.workflow) == 'undefined') {
      wx.showToast({
        title: '数据错误',
        icon: 'error',
        duration: 2000
      })
      // 导航到关卡列表
      wx.redirectTo({
        url: 'index',
      })
      return
    } else {
      this.workflow = this.checkpoint.workflow
      this.step = this.checkpoint.workflow.step
    }
    console.log('workflow', this.workflow, this.step)
    this.getTask()
  },

  getTask() {
    this.task = this.workflow.flow[this.step]
    console.log('task', this.task)
    this.setData({
      message_image: '',
      message_image_css: '',
      message_front_image: '',
      message_front_image_css: '',
      message_content: '',
      message_content_css: '',
      message_content_all_css: '',
      task_type: 0,
      show_next: false,
      show_gps: false,
      show_beacon: false,
      show_prompt: false,
      show: false,
    })

    if (this.task.type > 299) {
      // 内部处理
      if (this.task.type === 300) {
        return this.exitTask()
      }

      // 处理命令
      this.doOperation(this.task.content)

      // 处理完毕，进入下一个流程
      this.getNextTask()
    } else {
      // 需要显示的流程
      // 保存当前step
      this.workflow.step = this.step
      saveCheckpointList(this.checkpoint_list)
      const taskType = [100, 101, 102, 105, 106]
      if (taskType.indexOf(this.task.type) > -1) {
        wx.redirectTo({
          url: '../task/t' + this.task.type + '?id=' + this.checkpoint.code,
        });
        return
      }

      // 显示UI
      switch (this.task.type) {
        case 100:
          this.setTaskMessage(this.task);
          break;
        case 101:
          this.setGPSMessage(this.task);
          break;
        case 102:
          this.setBeaconMessage(this.task);
          break;
        case 103:
          this.setCheckMessage(this.task);
          break;
        case 104:
          this.setTaskKeyMessage(this.task);
          break;
        case 150:
          wx.redirectTo({
            url: '../game/g150?id=' + this.checkpoint.code,
          });
          break;
        case 200:
          this.setTaskQuestion(this.task);
          break;
        case 302:
          this.setTaskQuestion(this.task);
          break;
      }
    }


  },

  getNextTask() {
    this.step++

    // 提取下一个任务
    this.getTask();
  },

  setTaskMessage(task) {
    const content = task.content.trim()
    this.setData({
      message_image: task.image,
      message_image_css: task.image_css,
      message_front_image: task.front_image,
      message_front_image_css: task.front_image_css,
      message_content: content == '' ? [] : content.split('\n'),
      message_content_css: task.content_css,
      message_content_all_css: task.content_all_css,
      show_next: true,
      task_type: 100,
      show: true,
    })

  },

  setTaskKeyMessage(task) {
    const content = task.content.trim() + '\n' + wx.getStorageSync(task.keyname)
    this.setData({
      message_image: task.image,
      message_image_css: task.image_css,
      message_front_image: task.front_image,
      message_front_image_css: task.front_image_css,
      message_content: content == '' ? [] : content.split('\n'),
      message_content_css: task.content_css,
      message_content_all_css: task.content_all_css,
      show_next: true,
      task_type: 100,
      show: true,
    })

  },

  setGPSMessage(task) {
    const content = task.content.trim()
    this.setData({
      message_image: task.image,
      message_image_css: task.image_css,
      message_front_image: task.front_image,
      message_front_image_css: task.front_image_css,
      message_content: content == '' ? [] : content.split('\n'),
      message_content_css: task.content_css,
      message_content_all_css: task.content_all_css,
      task_type: 101,
      show_gps: true,
      show: true,
    })
  },

  setBeaconMessage(task) {
    const content = task.content.trim()
    this.setData({
      message_image: task.image,
      message_image_css: task.image_css,
      message_front_image: task.front_image,
      message_front_image_css: task.front_image_css,
      message_content: content == '' ? [] : content.split('\n'),
      message_content_css: task.content_css,
      message_content_all_css: task.content_all_css,
      task_type: 102,
      show_beacon: true,
      show: true,
    })
  },

  setCheckMessage(task) {
    const content = task.content.trim()
    this.setData({
      message_image: task.image,
      message_image_css: task.image_css,
      message_front_image: task.front_image,
      message_front_image_css: task.front_image_css,
      message_content: content == '' ? [] : content.split('\n'),
      message_content_css: task.content_css,
      message_content_all_css: task.content_all_css,
      message_confirm: task.confirm,
      task_type: 103,
      // show_beacon: true,
      show: true,
    })
  },

  setTaskQuestion(task) {
    // 选项随机
    if (!Array.prototype.shuffle) {
      Array.prototype.shuffle = function () {
        for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
        return this;
      };
    }
    task.item_list.shuffle();

    const content = task.content.trim()
    this.setData({
      message_image: task.image,
      message_image_css: task.image_css,
      message_front_image: task.front_image,
      message_front_image_css: task.front_image_css,
      message_content: content == '' ? [] : content.split('\n'),
      message_content_css: task.content_css,
      message_content_all_css: task.content_all_css,
      question_item_list: task.item_list,
      task_type: 200,
      show: true,
    })

  },

  setWorkFlow(flow) {
    this.workflow = flow
    this.checkpoint.workflow = this.workflow
    this.step = this.checkpoint.workflow.step
    // console.log('set flow', flow)
  },

  onSelectQuestionEnd(e) {
    const index = e.currentTarget.dataset.id
    const flow = {
      flow: this.task.item_list[index].flow,
      step: 0
    }

    // 提示信息
    const prompt = this.task.item_list[index].prompt === undefined ? '' : this.task.item_list[index].prompt.trim()
    if (prompt.length > 0) {
      this.setData({
        message_prompt: prompt,
        show: false,
        show_prompt: true
      })

      let self = this
      setTimeout(function () {
        self.setWorkFlow(flow)
        self.getTask()
      }, 3000)

      return
    }
    this.setWorkFlow(flow)
    console.log('new task flow', this.workflow)

    this.getTask()
  },

  onShowPromptEnd() {
    // this.setWorkFlow(flow)
    // console.log('new task flow', this.workflow)

    // this.getTask()
  },

  onSelectConfirmEnd(e) {
    this.setData({
      // task_type: 0,
      show_next: true
    })
  },

  onSelectMessageEnd(e) {
    // 清理数据
    this.setData({
      show_next: false
    })

    this.getNextTask()
  },

  onSelectGPSEnd(e) {
    // this.getRang(30.63629937065972, 104.32721245659722)
    wx.showLoading({
      title: '扫描任务...',
    });

    let self = this
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy

        // console.log('location', res)
        self.getRang(latitude, longitude)
      }
    })
  },

  onSelectBeaconEnd(e) {
    console.log('on beacon', this.task.beacon)
    let self = this
    this.setData({
      show_beacon: false
    })
    wx.showLoading({
      title: '开始搜索...',
    });

    // 创建定时器
    this.beacon_flag = false
    var myTimer = setInterval(() => {
      wx.hideLoading()
      // 更新beacons数据
      if (self.beacon_flag) {
        wx.showToast({
          title: '恭喜你找到了',
          icon: 'success',
          duration: 2000
        })

        setTimeout(function () {
          self.getNextTask()
        }, 2000);

      } else {
        wx.showToast({
          title: '没有找到，再试试',
          icon: 'error',
          duration: 3000,
          mask: true
        })

        setTimeout(function () {
          self.setData({
            show_beacon: true
          })
        }, 2000);
      }

      wx.stopBeaconDiscovery({
        success: res => {
          console.log("停止搜索iBeacon设备");
          // 清空beacons数据
        },
        fail: err => {
          console.error("停止iBeacon搜索失败:", err);
        }
      });
      clearInterval(myTimer); //销毁定时器 
    }, 3000) //定时循环的时长 毫秒 ，1秒=1000毫秒


    // 初始化iBeacon
    wx.startBeaconDiscovery({
      uuids: [this.task.beacon],
      success: res => {
        console.log("开始搜索iBeacon设备");
      },
      fail: err => {
        console.error("启动iBeacon搜索失败:", err);
      }
    });

    // 监听iBeacon设备变化
    wx.onBeaconUpdate(res => {
      console.log("发现新的iBeacon设备:", res.beacons);
      self.beacon_flag = true
    });

  },

  getRang(lat, long) {
    let gps = this.checkpoint.gps.split(",")
    let distance = calculateDistance(lat, long, gps[0], gps[1])
    console.log(distance, this.task.range)

    if (distance < this.task.range) {
      wx.hideLoading()
      this.getNextTask()
    } else {
      wx.showToast({
        title: '距离' + distance + '米',
        icon: 'error',
        duration: 3000
      })
    }
  },

  async exitTask() {
    console.log('exit task')
    // return
    // 更新场地状态, 保存数据
    if (this.checkpoint.status < 3) {
      this.checkpoint.status = 3
      // this.checkpoint.pic = this.checkpoint.pic2
    }

    // 计算剩余任务
    let finishCount = 0
    // let totalCount = wx.getStorageSync('totalCount')
    let totalCount = 0
    this.checkpoint_list.forEach(function (checkpoint) {
      // 计算完成的任务数
      if (checkpoint.group === 'MAIN') {
        totalCount++
        if (checkpoint.status > 2) {
          // console.log(checkpoint)
          finishCount++
        }
      }
    })

    // 保存数据到本地
    saveCheckpointList(this.checkpoint_list)
    wx.setStorageSync('welcome', false)
    wx.setStorageSync('totalCount', totalCount)
    wx.setStorageSync('finishCount', finishCount)
    wx.setStorageSync('leftCount', totalCount - finishCount)

    // 保存数据到远程
    const res = await saveRemoteRecord()
    // console.log('save record', res.result)

    // 完成关卡任务，退出
    if (res.result) {
      wx.redirectTo({
        url: 'index'
      })
    } else {
      wx.showToast({
        title: '保存数据失败',
      })
    }
  },

  doOperation(operation_list) {
    // 如果任务已经完成，跳过晋级书
    if (this.checkpoint.status == 3) {
      return
    }
    const operations = operation_list.split(';')
    let gold = 0
    let value = 0
    console.log('operations', operations)
    for (let index = 0; index < operations.length; index++) {
      let operation = operations[index]
      console.log('operation', operation)
      if (operation.length == 0) {
        continue
      }

      // 检查命令
      const fword = operation.slice(0, 1)
      switch (fword) {
        case '+': // 增加金币
          gold = wx.getStorageSync('gold')
          value = Number(operation.slice(1))
          wx.setStorageSync('gold', gold + value)

          // 保存到远程
          saveRemoteGold();
          break

        case '-': // 减少金币
          gold = wx.getStorageSync('gold')
          value = Number(operation.slice(1))
          gold - value > 0 ? wx.setStorageSync('gold', gold - value) : wx.setStorageSync('gold', 0)

          // 保存到远程
          saveRemoteGold();
          break

        case 'S': // 启动任务（可以通过定位显示任务）
          value = Number(operation.slice(1))
          this.checkpoint_list.forEach(checkpoint => {
            if (checkpoint.code == value) {
              // console.log('enable checkpoint', checkpoint)
              checkpoint.enable = true
              checkpoint.group = 'MAIN'
            }
          });

          // 保存到本地
          saveCheckpointList(this.checkpoint_list)
          break

        case 'H': // 隐藏任务（同时不能定位）
          value = Number(operation.slice(1))
          this.checkpoint_list.forEach(checkpoint => {
            if (checkpoint.code == value) {
              // console.log('hide checkpoint', checkpoint)
              checkpoint.display = false
              checkpoint.enable = false
            }
          });

          // 保存到本地
          saveCheckpointList(this.checkpoint_list)
          break


        case 'K': // 创建随机密码
          // value = Number(operation.slice(1))
          // console.log('create key', value)
          let keyword = ''
          for (let i = 0; i < 3; i++) {
            let c = Math.floor(Math.random() * 10)
            keyword += c.toString()
          }
          // console.log(keyword)
          wx.setStorageSync(operation, keyword)
          break
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})